package cn.xiaolang.function.network.communicate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {

    public static void main(String[] args) throws IOException {
        // 创建一个服务端对象，并指定服务端的端口号
        ServerSocket server = new ServerSocket(10010);
        //获取客户端对象，明确是哪个客户端发来的数据;PS: 执行到此处时，程序处于阻塞状态，直到客户端连接，转为运行状态
        Socket s = server.accept();

        System.out.println(s.getInetAddress().getHostAddress() + " connected! ");
        //获取客户端输入流对象，用来读取从客户端接收来的数据
        InputStream input = s.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(input));
        String line = null;
        while ((line = br.readLine()) != null) {
            //如果读取到的数据为over，那么关闭与客户端建立的连接
            if (line.equals("over")) {
                s.close();
            }
            System.out.println("[client] "+s.getInetAddress().getHostAddress() + " send data: " + line);
            //向客户端返回数据，返回接收到数据的大写
            OutputStream out = s.getOutputStream();
            out.write(line.toUpperCase().getBytes());
        }
        server.close();
    }

}
